package com.weir.resilience4j.consumer;

import java.time.Duration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.retry.Retry;
import io.github.resilience4j.retry.RetryConfig;
import io.vavr.control.Try;

@SpringBootApplication
public class WeirResilience4jConsumerApplication {

	public static void main(String[] args) {
		SpringApplication.run(WeirResilience4jConsumerApplication.class, args);
	}

	@Bean
	public RestTemplate restTemplate(RestTemplateBuilder builder) {
		return builder.build();
	}
}

@RestController
class HelloController {
	@Autowired
	private HelloService helloService;
	@Autowired
	private HelloService2 helloService2;
	@Autowired
	private HelloService3 helloService3;

	@GetMapping("/hell/{name}")
	public String hello1(@PathVariable String name) {
		// 重试功能Retry
		RetryConfig config = RetryConfig.custom().maxAttempts(3).waitDuration(Duration.ofMillis(5000)).build();
		Retry retry = Retry.of("id", config);
		Try<String> result = Try.ofSupplier(Retry.decorateSupplier(retry, () -> helloService.hello(name)));

		return result.get();
	}
//CircuitBreaker断路器
	@GetMapping("/hell2/{name}")
	public String hello2(@PathVariable String name) {
		return helloService2.hello2(name);
	}
	//限流
	@GetMapping("/hell3/{name}")
	public void rateLimiter2(@PathVariable String name) {
	    helloService3.hello2(name);
	}
}